package com.itheima.filter;

import com.itheima.exception.BusinessException;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        StringBuffer url = req.getRequestURL();
        String uri = req.getRequestURI();

        if(uri.contains("/login")){
            chain.doFilter(req, response);
            return;
        }
        String token=req.getHeader("token");
        if(token==null){
            resp.setStatus(401);
            log.error("token is null");
            return;
        }
        try {
            Claims claims = JwtUtils.parseJWT(token);
            log.info("claims:{}",claims);
        }catch (Exception e){
            resp.setStatus(401);
            log.error("令牌解析失败:{}",e.getMessage());
            return;
        }
        chain.doFilter(request, response);

    }
}
